//获取应用实例
const app = getApp()
Page({
  onLoad(options) {
    this.setData({
      redirect: options.redirect
    })
  },
  data: {
    countDownVisible: false,
    //保存输入的手机号码
    mobile: '',
    code: '',
    redirect: ''
  },
  //定义手机号码正则
  checkmobile() {
    const mobileReg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
    const mobilevoild = mobileReg.test(this.data.mobile.trim())
    if (!mobilevoild) return wx.utils.toast('请输入合法的手机号码')
    return mobilevoild
  },

  //验证验证码
  checkcode() {
    const codeReg = /^\d{6}$/
    const codeVoild = codeReg.test(this.data.code.trim())
    if (!codeVoild) return wx.utils.toast('请输入合法的验证码')
    return codeVoild
  },
  //获取验证码
  async getcode() {
    this.checkmobile()
    if (!this.checkmobile()) return
    const res = await wx.http.get('/code', { mobile: this.data.mobile })
    // console.log(res)
    this.setData({
      code: res.data.code
    })
    //成功提示用户
    wx.utils.toast('验证码已发送')
    //开始倒计时
    this.setData({
      countDownVisible: true
    })
  },
  //复制验证码功能
  copyCode() {
    wx.setClipboardData({
      data: this.data.code
    })
  },
  //登录功能
  async onSubmit() {
    //判断手机号码是否合法
    if (!this.checkmobile()) return wx.utils.toast('请输入手机号')
    if (!this.checkcode()) return wx.utils.toast('请输入验证码')
    const res = await wx.http.post('/login', { mobile: this.data.mobile, code: this.data.code })
    //登录成功提示
    wx.utils.toast('登录成功')
    console.log('登录', res);
    //将token存储到本地存储和App函数里面
    wx.setStorageSync('token', res.data.token)
    // app.token = res.data.token
    app.setToken(res.data.token, res.data.refreshToken)
    // 重定向至登录前的页面 
    const redirect = this.data.redirect || 'pages/my/index'
    wx.reLaunch({
      url: '/' + redirect
    })
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },


})
